package com.shop.loan.proxy;

import com.shop.loan.mapper.BlacklistByMybatisMapper;
import com.shop.loan.model.BlackList;
import com.shop.loan.model.entity.BlacklistByMybatis;
import com.shop.loan.redis.RedisCache;
import com.shop.loan.redis.RedisUtil;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.DataProxy;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BlackListProxy implements DataProxy<BlackList> {

    @Resource
    RedisUtil redisUtil;

    @Resource
    BlacklistByMybatisMapper blacklistByMybatisMapper;

    @Override
    public void afterAdd(BlackList blackList) {
        if (blackList.getContent().contains(".")) {
            updateBlackCache();
        }
    }

    @Override
    public void afterDelete(BlackList blackList) {
        if (blackList.getContent().contains(".")) {
            redisUtil.del(RedisCache.userLoginFailNumIp + blackList.getContent());
            updateBlackCache();
        }
    }

    /**
     * 修改黑名单缓存
     */
    private void updateBlackCache() {
        redisUtil.del(RedisCache.blackListByIp);
        List<BlacklistByMybatis> blacklistByMybatisList = blacklistByMybatisMapper.selectIpByList();
        if (blacklistByMybatisList == null || blacklistByMybatisList.size() == 0) {
            return;
        }
        for (BlacklistByMybatis blacklistByMybatis : blacklistByMybatisList) {
            redisUtil.hset(RedisCache.blackListByIp, blacklistByMybatis.getContent(), blacklistByMybatis.getContent());
        }
    }

}
